﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Windows.Media.Imaging;
using System.Resources;
using System.Configuration;
using System.Globalization;
using System.Threading;
using System.Windows.Data;
using System.Collections;
using Gaiocorp.SLMapViewer.Legend;
using SilverlightDragNDrop;
using Gaiocorp.SLMapViewer.Resources;


namespace Gaiocorp.SLMapViewer
{
    public partial class MapControl : UserControl
    {
        #region Private
        private Point lastMousePosition;
        public Int32 X = 0, Y = 0;
        bool dragInProgress = false;
        PointCollection userPoints = new PointCollection();
        double lastX = 0.0;
        double lastY = 0.0;
        double totalDistance = 0.0;
        Point pntUserClick;
        string xmlString = string.Empty;
        private LegendLayers allLyrs = new LegendLayers();
        private List<Point> _points = new List<Point>();
        private Line _aSegment = new Line();
        private List<Line> _Segments = new List<Line>();
        private System.Windows.Shapes.Path _MeasureLine = new System.Windows.Shapes.Path();
        private bool _kioskMode = false;
        private double _mapWidth = 0.0;
        private double _mapHeight = 0.0;
        private bool _internalControls = false;
        private bool _debugOn = false;
        private string _mapfile = string.Empty;
        private string _XCoordName = string.Empty;
        private string _YCoordName = string.Empty;
        List<DependencyObject> elts = new List<DependencyObject>();
        private IDictionary<string, string> _parameters = null;
        #endregion
        
        #region Properties
        public IDictionary<string, string> Parameters
        {
            get { return _parameters; }
            set 
            {
                _parameters = value;
                SetParameters(_parameters);
            }
        }

        public double MapWidth
        {
            get { return _mapWidth; }
            set
            {
                if (value == 0) value = 500;
                _mapWidth = value;
             }
        }

        public double MapHeight
        {
            get { return _mapHeight; }
            set
            {
                if (value == 0) value = 500;
                _mapHeight = value;
            }
        }
        public string MapFile
        {
            get { return _mapfile; }
            set { _mapfile = value; }
        }
        public bool KioskMode
        {
            get { return _kioskMode; }
            set { 
                _kioskMode = value;
               
            }
        }

        public bool InternalControls
        {
            get { return _internalControls; }
            set { _internalControls = value; }
        }

        public bool DebugOn
        {
            get { return _debugOn; }
            set { _debugOn = value; }
        }

        

        public string XCoordName
        {
            get { return _XCoordName; }
            set { _XCoordName = value; }
        }
        public string YCoordName
        {
            get { return _YCoordName; }
            set { _YCoordName = value; }
        }
        #endregion

        #region Constructors
        public MapControl()
        {
            InitializeComponent();
            legend.ParentMap = this;
            mapTools.ParentMap = this;
            this.Loaded += new RoutedEventHandler(Page_Loaded);
            legend.gridLegend.Tag = null;

            try
            {
                 // Get the culture of the currently executing thread.
            // The value of ci will determine the culture of
            // the resources that the resource manager retrieves.
            CultureInfo ci = Thread.CurrentThread.CurrentUICulture;
            
            ApplicationStrings.Culture = ci;
            }
            catch (Exception)
            {
                
            }
        }
        public MapControl(IDictionary<string, string> parameters)
        {
            this.Parameters = parameters;
            try
            {
                InitializeComponent();
            }
            catch (Exception)
            {}
            
            this.Loaded += new RoutedEventHandler(Page_Loaded);
            SetParameters(parameters);
            InitializeRightMouseButton();
            legend.gridLegend.Tag = null;

            string c = System.Threading.Thread.CurrentThread.CurrentCulture.Name.ToString();

            // Get the culture of the currently executing thread.
            // The value of ci will determine the culture of
            // the resources that the resource manager retrieves.
            CultureInfo ci = Thread.CurrentThread.CurrentUICulture;
            
            ApplicationStrings.Culture = ci;
        }
        #endregion

        #region Public Methods
        public void ZoomToFeature(string layerName, string pkField, int pkValue)
        {
            string sWhere = pkField + "=" + pkValue;
            stxtRequest.Text = "<REQUEST action='AttributeQuery' layer='" + layerName + "' where='" + sWhere + "' sessionid='' />";
        }

       #endregion

        #region Initialization 
        void SetParameters(IDictionary<string, string> parameters)
        {
            if (parameters == null) { return; }

            //Set Properties
            this.MapFile = _parameters["Mapfile"];

            this.Width = Convert.ToInt32(_parameters["Width"]);
            this.Height = Convert.ToInt32(_parameters["Height"]);

            this.MapWidth = Convert.ToInt32(_parameters["Width"]);
            this.MapHeight = Convert.ToInt32(_parameters["Height"]);

            if (_parameters["InternalControls"] == "1")
                this.InternalControls = true;
            else this.InternalControls = false;

            if (_parameters["Mode"] != "KIOSK")
                this.KioskMode = false;
            else this.KioskMode = true;

            if (_parameters["DebugOn"] == "1")
                this.DebugOn = true;
            else this.DebugOn = false;

          

        }
       
       void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_parameters == null)
                {
                    _parameters = Application.Current.Host.InitParams;
                    SetParameters(_parameters);
                }
                InitializeControlLocations();
                mapTools.Parameters = _parameters;
                mapTools.ParentMap = this;
                legend.ParentMap = this;

                this.Width = MapWidth;
                this.Height = MapHeight;

                DragManager dm = new DragManager(LayoutRoot);
                dm.EnableDragableElement(brdMeasureToolTip);
                dm.EnableDragableElement(brdResults);
                dm.EnableDragableElement(brdQuery);
                dm.EnableDragableElement(brdPrint);
                dm.EnableDragableElement(ErrorDialog);

                InitializeMouseWheel();

                HtmlElement txtRequest = null;
                try
                {
                    txtRequest = HtmlPage.Document.GetElementById(_parameters["RequestControlID"].ToString());
                }
                catch { }
                if (txtRequest != null)
                {
                    if (txtRequest.GetProperty("value").ToString() == string.Empty)
                    {
                        stxtRequest.Text = "<REQUEST action='InitMap' reset='yes' sessionid='" + _parameters["SessionID"] + "' mapwidth='" + MapWidth.ToString() + "'" + " mapheight='" + MapHeight.ToString() + "' mapfile='" + MapFile + "' />";
                    }
                    else
                    {
                        stxtRequest.Text = "<REQUEST " + txtRequest.GetProperty("value").ToString() + " reset='yes' sessionid='" + _parameters["SessionID"] + "' mapwidth='" + MapWidth.ToString() + "'" + " mapheight='" + MapHeight.ToString() + "' mapfile='" + MapFile + "' />";

                    }
                }
                else { stxtRequest.Text = "<REQUEST action='InitMap' reset='yes' sessionid=''" + " mapwidth='" + MapWidth.ToString() + "'" + " mapheight='" + MapHeight.ToString() + "' mapfile='" + MapFile + "' />"; }
            }
            catch { }
        }
        /// <summary>
        /// Deprecated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
     
       void Content_Resized(object sender, EventArgs e)
        {
            //Sv.Width = gridLegCont.ColumnDefinitions[Grid.GetColumn(Sv as FrameworkElement)].ActualWidth;
            // Sv.Height = gridLegCont.RowDefinitions[Grid.GetRow(Sv as FrameworkElement)].ActualHeight;
        }
       /// <summary>
       /// Positions the map tools
       /// </summary>
       private void InitializeControlLocations()
       {
            this.cnvMap.Width = this.MapWidth;
            this.cnvMap.Height = this.MapHeight;
            this.MapImg.Width = this.MapWidth;
            this.MapImg.Height = this.MapHeight;
            rectMap.Width = MapImg.Width;
            rectMap.Height = MapImg.Height;
           

            // Hide kiosk-specific tools if not in kiosk mode
            if (!this.KioskMode)
            {
                //Align toolbar
                mapTools.brdToolbar.SetValue(Canvas.TopProperty, Convert.ToDouble(0));
                mapTools.brdToolbar.SetValue(Canvas.LeftProperty, Convert.ToDouble(0));
                mapTools.cnvKioskTools.Visibility = Visibility.Collapsed;
                mapTools.PanLeftKiosk.Visibility = Visibility.Collapsed;
                mapTools.PanRightKiosk.Visibility = Visibility.Collapsed;
                mapTools.PanTopKiosk.Visibility = Visibility.Collapsed;
                mapTools.PanDownKiosk.Visibility = Visibility.Collapsed;
            }
            else  //Kiosk mode
            { 
                //Hide Legend
                expLegend.Visibility = Visibility.Collapsed;

                //Display 'kiosk buttons'
                mapTools.brdToolbar.Visibility = Visibility.Collapsed;

                mapTools.PanLeftKiosk.Visibility = Visibility.Visible;
                mapTools.PanRightKiosk.Visibility = Visibility.Visible;
                mapTools.PanTopKiosk.Visibility = Visibility.Visible;
                mapTools.PanDownKiosk.Visibility = Visibility.Visible;

                mapTools.PanLeftKiosk.SetValue(Canvas.LeftProperty, Convert.ToDouble(0));
                mapTools.PanLeftKiosk.SetValue(Canvas.TopProperty, MapHeight/2);
                mapTools.PanRightKiosk.SetValue(Canvas.LeftProperty, MapWidth - mapTools.PanRightKiosk.Width);
                mapTools.PanRightKiosk.SetValue(Canvas.TopProperty, MapHeight / 2);

                mapTools.PanTopKiosk.SetValue(Canvas.LeftProperty, MapWidth/2);
                mapTools.PanTopKiosk.SetValue(Canvas.TopProperty, Convert.ToDouble(0));
                mapTools.PanDownKiosk.SetValue(Canvas.LeftProperty, MapWidth / 2);
                mapTools.PanDownKiosk.SetValue(Canvas.TopProperty, MapHeight - mapTools.PanDownKiosk.Height - brdStatus.Height);
            }

            this.LayoutRoot.Width = this.MapWidth;
            this.LayoutRoot.Height = this.MapHeight;

            // Set legend controls
            expLegend.SetValue(Canvas.LeftProperty, MapWidth - 301);
           
            legend.cnvLegend.MaxWidth = MapImg.Width - 50;
            legend.cnvLegend.Height = MapImg.Height - 50;
            RowDefinition treeRow = legend.gridLegend.RowDefinitions[2];
            treeRow.Height = new GridLength(legend.cnvLegend.Height - 60);
            legend.treeLegend1.Height = treeRow.Height.Value; // Set explicit height so as scrollbars will display if required.
            legend.treeLegend1.Background = new SolidColorBrush(legend.BackroundColor);
            
            //Display debug window?
            if (DebugOn)
            {
                gridDebug.Visibility = Visibility.Visible;
                DragManager dm = new DragManager(LayoutRoot);
                dm.EnableDragableElement(gridDebug);
            }
            else gridDebug.Visibility = Visibility.Collapsed;

            //Set the status bar
            brdStatus.SetValue(Canvas.TopProperty, (MapImg.Height - brdStatus.Height));
            brdStatus.SetValue(Canvas.LeftProperty, (double)0);
            brdStatus.Width = MapImg.Width;
            
            // Center wait window
            brdWait.SetValue(Canvas.TopProperty, this.MapImg.Height / 2 - brdWait.Height / 2);
            brdWait.SetValue(Canvas.LeftProperty, this.MapImg.Width / 2 - brdWait.Width / 2);
            
            //Center error window
            ErrorDialog.SetValue(Canvas.TopProperty, this.MapImg.Height / 2 - ErrorDialog.Height / 2);
            ErrorDialog.SetValue(Canvas.LeftProperty, this.MapImg.Width / 2 - ErrorDialog.Width / 2);
           
            //Resize results window
            try
            {
                gridDataResults.Width = (this.MapImg.Width - 50);
                //gridDataResults.Height = (this.MapImg.Height / 4);
            }
            catch
            {
                gridDataResults.Width =400;
            }
            //Resize query window
            try
            {
                brdQuery.MaxHeight = (this.MapImg.Height - 50);
                brdQuery.MaxWidth = (this.MapImg.Width - 50);
            }
            catch
            {
                brdQuery.MaxHeight = 450;
                brdQuery.MaxWidth = 450;
            }
            gridQuery.MaxHeight = brdQuery.MaxHeight;
            gridQuery.MaxWidth = brdQuery.MaxWidth;
       }
        #endregion

       #region Legend Expander
       private void expLegend_Expanded(object sender, RoutedEventArgs e)
        {
            expLegend.Width = 300;
            expLegend.Height = MapImg.Height - 85;
        }

        private void expLegend_Collapsed(object sender, RoutedEventArgs e)
        {
            expLegend.Height = 30;
            expLegend.Width = 300;
        }
        #endregion

        # region Load Map and Async response/requests
        public void stxtRequest_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            if (txt.Text != string.Empty)
            {
                LoadMap();
            }

        }
        [ScriptableMember]
        public void LoadMap()
        {
            try
            {
                brdWait.Visibility = Visibility.Visible;
                string serviceUrl = _parameters["MapServiceUrl"].ToString();
                Uri serviceUri = new Uri(serviceUrl);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUri);
                request.Method = "POST";
                request.ContentType = "text/xml";
                AsyncCallback asyncCallback = new AsyncCallback(RequestProceed);
                IAsyncResult a = request.BeginGetRequestStream(asyncCallback, request); // dies here
            }
            catch (Exception)
            {
                //Log.Text = e1.StackTrace;
            }
        }

        void RequestProceed(IAsyncResult asyncResult)
        {
            this.Dispatcher.BeginInvoke(delegate() //If you dont put this line you get access errors.
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asyncResult));

                string requestXML = this.stxtRequest.Text;
                //Make sure its a valid xml
                if (requestXML != string.Empty && requestXML.Trim().StartsWith("<") && requestXML.Trim().EndsWith(">"))
                {
                    postDataWriter.Write(requestXML);
                    postDataWriter.Close();
                    request.BeginGetResponse(new AsyncCallback(ResponseProceed), request);
                }
            });
        }

        void ResponseProceed(IAsyncResult asyncResult)
        {
            this.Dispatcher.BeginInvoke(delegate() //If you dont put this line you get access errors.
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                    StreamReader responseReader = new StreamReader(response.GetResponseStream());
                    String responseString = responseReader.ReadLine();
                    stxtResponse.Text = responseString;
                    XDocument doc = XDocument.Parse(responseString);
                    XElement xEl1 = doc.Element("RESPONSE");
                    
                    //Check if we got returned any errors
                    XElement xElError = xEl1.Element("ERROR");
                    if (xElError != null)
                    {
                        //Display Error window
                        ErrorDialog.Visibility = Visibility.Visible;
                        ErrorDialog.txbErrBody.Text = xElError.FirstNode.ToString();
                        return;
                    }
                    else
                    {
                        XElement xEl2 = xEl1.Element("IMAGE");
                        if (xEl2 != null)
                        {
                            //this.cnvMap.Width = (double)xEl2.Attribute("width");
                            //this.cnvMap.Width = (double)xEl2.Attribute("height");
                            string strIMageURL = (string)xEl2.Attribute("imageURL");
                            stxtXMin.Text = (string)xEl2.Attribute("minx");
                            stxtXMax.Text = (string)xEl2.Attribute("maxx");
                            stxtYMin.Text = (string)xEl2.Attribute("miny");
                            stxtYMax.Text = (string)xEl2.Attribute("maxy");
                            txtScale.Text = (string)xEl2.Attribute("scale");
                            //Populate selection flag
                            try
                            {
                                stxtHasSelection.Text = (string)xEl2.Attribute("selectionmap");
                            }
                            catch
                            {
                                stxtHasSelection.Text = "no";
                            }
                            Image img = new Image();
                            Uri uri = new Uri(strIMageURL.ToString(), UriKind.Absolute);
                            ImageSource imgSource = new BitmapImage(uri);
                            this.MapImg.Source = imgSource;
                            //TranslateTransform transform = GetTranslateTransform(MapImg);
                            //transform.X += 0;
                            //transform.Y += 0;

                            //Canvas.SetLeft(cnvMap, 0);
                            //Canvas.SetTop(cnvMap, 0);
                            MapImg.SetValue(Canvas.TopProperty, 0.0);
                            MapImg.SetValue(Canvas.LeftProperty, 0.0);
                            //Canvas.SetLeft(MapImg, 0);
                            //Canvas.SetTop(MapImg, 0);
                            myStoryboard.Begin();

                            //Populate Legend control 
                            XElement xElm = doc.Element("LEGEND");
                            allLyrs=legend.PopulateLegend(responseString);
                        }

                        //Populate the identify/table grid control
                        CreateIdentifyGrid(responseString);

                        //Populate the layer drop down in the Query dialog
                        BindCboToLayers();

                        //Check if we got return an external URL
                        XElement xElURL = xEl1.Element("EXTERNALURL");
                        if (xElURL != null)
                        {
                            GoToUrl(xElURL.Value);
                        }
                        //Check if we got return an external URL
                        XElement xElPrint = xEl1.Element("PRINTIMAGE");
                        if (xElPrint != null)
                        {
                           ComboBoxItem cbi = (ComboBoxItem)cboPaperSizes.SelectedItem;
                           Uri serviceUri = new Uri( _parameters["MapServiceUrl"].ToString());
                           Uri printUri = new Uri(serviceUri.Scheme + "://" + serviceUri.Host  + ":" + serviceUri.Port+ "/PrintTemplates/GenPrintTemplate.aspx?pso=" + cbi.Tag.ToString() + "&title=" + txtPrintTitle.Text);
                           GoToUrl(printUri.ToString());
                        }
                    }
                }
                catch (Exception Ex)
                {
                    ErrorDialog.Visibility = Visibility.Visible;
                    ErrorDialog.txbErrBody.Text = Ex.Message.ToString();
                }
                finally
                {
                    //Hide the 'please wait' window
                    brdWait.Visibility = Visibility.Collapsed;
                }
            }
            );


        }
        # endregion

        #region Mouse and Keyboard Events on Map Image

        private void MapImg_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (stxtActiveTool.Text != "MEASURE")
            {
                if (this.dragInProgress && e.GetPosition(MapImg).Y > 24)
                {
                    this.dragInProgress = false;
                    ClearDynamicShapes();
                    switch (stxtActiveTool.Text)
                    {
                        case "ZOOMIN":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='ZoomInBox' sessionid='" + _parameters["SessionID"] + "' />";
                            break;
                        case "ZOOMOUT":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='ZoomOutBox' sessionid='" + _parameters["SessionID"] + "' />";
                            break;
                        case "PAN":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='Pan' sessionid='" + _parameters["SessionID"] + "' />";
                            break;
                        case "ADDPIN":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='GetXYButton' sessionid='" + _parameters["SessionID"] + "' />";
                            break;
                        case "SELECT":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='SELECT' sessionid='" + _parameters["SessionID"] + "' />";
                            break;
                        case "INFO":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='INFO' sessionid='" + _parameters["SessionID"] + "' />";
                            brdResults.Visibility = Visibility.Visible;
                            brdResults.SetValue(Canvas.TopProperty, Convert.ToDouble(50));
                            break;
                        case "HYPERLINK":
                            DoUrlRequest(pntUserClick.X, e.GetPosition(MapImg).X, pntUserClick.Y, e.GetPosition(MapImg).Y);
                            break;
                        case "MEASURE":

                            break;
                        case "ADDPNT":
                            this.stxtRequest.Text = "<REQUEST ymax='" + e.GetPosition(MapImg).Y.ToString() + "' xmax='" + e.GetPosition(MapImg).X.ToString() + "' ymin='" + pntUserClick.Y.ToString() + "' xmin='" + pntUserClick.X.ToString() + "' action='ADDSHPPNT' sessionid='" + _parameters["SessionID"] + "' />";
                            brdResults.Visibility = Visibility.Visible;
                            brdResults.SetValue(Canvas.TopProperty, Convert.ToDouble(50));
                            gridDataResults.IsReadOnly = false;
                            break;
                    }
                    MapImg.ReleaseMouseCapture();
                }
            }
            else
            {
                UserMeasureLine.Visibility = Visibility.Collapsed;
            }
        }

        private void MapImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
           
            if (e.GetPosition(MapImg).Y > 24)
            {
                dragInProgress = true;
                MapImg.CaptureMouse();
                pntUserClick = e.GetPosition(MapImg);
                if (stxtActiveTool.Text == "MEASURE")
                {
                    userPoints.Add(new Point(pntUserClick.X, pntUserClick.Y));
                    if (userPoints.Count > 1)
                     totalDistance = ReturnGeoLength(userPoints);
                    else totalDistance = 0.0;

                    txbTotalLength.Text = string.Format("{0:0.00}", totalDistance);

                    UserMeasurePolyLine.Points = userPoints;
                    lastX = pntUserClick.X;
                    lastY = pntUserClick.Y;
                   
                }
                else if (stxtActiveTool.Text == "ADDPIN")
                {
                    if (XCoordName != string.Empty && YCoordName != string.Empty)
                    {
                        Point pntRealPnt = pixel2point(e.GetPosition(MapImg).X, e.GetPosition(MapImg).Y);
                        GetCoordTb(pntRealPnt.X, pntRealPnt.Y);
                    }
                }
                else if (stxtActiveTool.Text == "PAN")
                {
                    lastMousePosition = e.GetPosition(LayoutRoot);
                }
            }
        }

        private void MapImg_MouseMove(object sender, MouseEventArgs e)
        {
           
            Point currentMousePosition = e.GetPosition(this.MapImg);

            if (stxtActiveTool.Text == "ZOOMIN" || stxtActiveTool.Text == "ZOOMOUT" || stxtActiveTool.Text == "SELECT")
            {
                if (dragInProgress && e.GetPosition(MapImg).Y > 24)
                {
                    double dblWidth = Math.Abs(currentMousePosition.X - pntUserClick.X);
                    double dblHeight = Math.Abs(currentMousePosition.Y - pntUserClick.Y);
                    if (pntUserClick.X < currentMousePosition.X && pntUserClick.Y < currentMousePosition.Y)
                    {
                        dynrectangle.Visibility = Visibility.Visible;
                        Canvas.SetLeft(dynrectangle, pntUserClick.X);
                        Canvas.SetTop(dynrectangle, pntUserClick.Y);

                        dynrectangle.Height = dblHeight;
                        dynrectangle.Width = dblWidth;
                    }

                }
            }
            else if (stxtActiveTool.Text == "PAN")
            {
                if (dragInProgress && e.GetPosition(MapImg).Y > 24)
                {
                    MapImg.SetValue(Canvas.LeftProperty, currentMousePosition.X - lastMousePosition.X);
                    MapImg.SetValue(Canvas.TopProperty, currentMousePosition.Y - lastMousePosition.Y);
                }
            }
            else if (stxtActiveTool.Text == "MEASURE")
            {
                if (UserMeasurePolyLine.Points.Count>0)
                {
                    MapImg.CaptureMouse();
                    UserMeasureLine.Visibility = Visibility.Visible;
                    brdMeasureToolTip.Visibility = Visibility.Visible;
                    UserMeasureLine.X1 = lastX;
                    UserMeasureLine.Y1 = lastY;
                    UserMeasureLine.X2 = currentMousePosition.X;
                    UserMeasureLine.Y2 = currentMousePosition.Y;
                    //Canvas.SetLeft(brdMeasureToolTip, currentMousePosition.X + 20);
                    //Canvas.SetTop(brdMeasureToolTip, currentMousePosition.Y - 30);
                    brdMeasureToolTip.Visibility = Visibility.Visible;
                    double segment_length = ReturnGeoLength(pntUserClick.X, pntUserClick.Y, currentMousePosition.X, currentMousePosition.Y);
                    txbMeasLength.Text = string.Format("{0:0.00}", segment_length.ToString());
                    if (UserMeasurePolyLine.Points.Count > 1)
                    {
                        totalDistance = ReturnGeoLength(userPoints) + segment_length;
                        txbTotalLength.Text = string.Format("{0:0.00}",  totalDistance);
                    }
                    else txbTotalLength.Text = string.Format("{0:0.00}", segment_length);
                    
                }
            }

            //Display real-world coords in status bar
            Point pntRealPnt = pixel2point(e.GetPosition(MapImg).X, e.GetPosition(MapImg).Y);
            stxtStatusBar.Text = ApplicationStrings.X.ToString() + string.Format("{0:0.00}", pntRealPnt.X) + "  " + ApplicationStrings.Y.ToString() + String.Format("{0:0.00}", pntRealPnt.Y);
        }

        private void MapImg_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (stxtActiveTool.Text == "MEASURE")
            {
                UserMeasurePolyLine.Points.Clear();
                UserMeasureLine.X1 = 0;
                UserMeasureLine.Y1 = 0;
                UserMeasureLine.X2 = 0;
                UserMeasureLine.Y2 = 0;
                brdMeasureToolTip.Visibility = Visibility.Collapsed;
                MapImg.ReleaseMouseCapture();
            }
        }

        private void DoUrlRequest(double xmin, double xmax, double ymin, double ymax)
        {
            LegendLayer aLyr = allLyrs.getActiveLayer();
            this.stxtRequest.Text = "<REQUEST ymax='" + ymax.ToString() + "' xmax='" + xmax.ToString() + "' ymin='" + ymin.ToString() + "' xmin='" + xmin.ToString() + "' action='HYPERLINK' layer='" + aLyr.Name + "' linkfield='" + aLyr.HLinkField + "' linkParams='" + aLyr.HLinkParams + "' sessionid='" + _parameters["SessionID"] + "' />";
        }

        private TranslateTransform GetTranslateTransform(UIElement element)
        {
            TranslateTransform translateTransform = null;
            if (element.RenderTransform is TranslateTransform)
            {
                translateTransform = element.RenderTransform as TranslateTransform;
            }
            else if (element.RenderTransform is TransformGroup)
            {
                TransformGroup group = element.RenderTransform as TransformGroup;
                foreach (GeneralTransform transform in group.Children)
                {
                    if (transform is TranslateTransform)
                    {
                        translateTransform = transform as TranslateTransform;
                    }
                }
            }
            else
            {
                translateTransform = new TranslateTransform();
                element.RenderTransform = translateTransform;
            }
            return translateTransform;
        }

        private void MapImg_MouseLeave(object sender, MouseEventArgs e)
        {
            if (this.dragInProgress)
            {
                this.dragInProgress = false;
                ClearDynamicShapes();
            }
        }

        protected void MapImg_LostMouseCapture(object sender, MouseEventArgs e)
        {
            if (this.dragInProgress)
            {
                this.dragInProgress = false;
                ClearDynamicShapes();

            }
        }

        private void ClearDynamicShapes()
        {
            dynrectangle.Height = 0;
            dynrectangle.Width = 0;
            Canvas.SetLeft(dynrectangle, -99);
            Canvas.SetTop(dynrectangle, -99);
            dynrectangle.Visibility = Visibility.Collapsed;
        }

        private void txtScale_KeyDown(object sender, KeyEventArgs e)
        {
            //Set map scale
            if (e.Key == Key.Enter)
            {
                stxtRequest.Text = "<REQUEST action='SetScale' scale='" + txtScale.Text + "' sessionid='" + _parameters["SessionID"] + "' />";
            }
        }
        # endregion

        # region XAML Control Events
        protected void OnMouseWheel(object sender, HtmlEventArgs e)
        {
            if (MapImg.IsHitTestVisible == false) return;
            double mouseDelta = 0;
            ScriptObject eventObject = e.EventObject;

            // Mozilla and Safari
            if (eventObject.GetProperty("detail") != null)
                mouseDelta = ((double)eventObject.GetProperty("detail"));

            // IE and Opera
            else if (eventObject.GetProperty("wheelDelta") != null)
                mouseDelta = ((double)eventObject.GetProperty("wheelDelta"));

            mouseDelta = Math.Sign(mouseDelta);

            if (mouseDelta > 0)
            {
                if (stxtRequest.Text == "<REQUEST action='ZoomIn' sessionid='" + _parameters["SessionID"] + "' />")
                {
                    stxtRequest_TextChanged(stxtRequest, null);
                }
                else
                    stxtRequest.Text = "<REQUEST action='ZoomIn' sessionid='" + _parameters["SessionID"] + "' />";
            }


            if (mouseDelta < 0)
            {
                if (stxtRequest.Text == "<REQUEST action='ZoomOut' sessionid='" + _parameters["SessionID"] + "' />")
                {
                    stxtRequest_TextChanged(stxtRequest, null);
                }
                else
                    stxtRequest.Text = "<REQUEST action='ZoomOut' sessionid='" + _parameters["SessionID"] + "' />";
            }


            if (mouseDelta != 0)
            {
                e.PreventDefault();
                eventObject.SetProperty("returnValue", false);
            }
        }

        protected void OnContextMenu(object sender, HtmlEventArgs e)
        {
            ScriptObject eventObject = e.EventObject;
            e.PreventDefault();
            e.StopPropagation();
            eventObject.SetProperty("returnValue", false);
        }

        private void InitializeMouseWheel()
        {
            HtmlPage.Window.AttachEvent("DOMMouseScroll", this.OnMouseWheel); // Mozilla
            HtmlPage.Window.AttachEvent("onmousewheel", this.OnMouseWheel);
            HtmlPage.Document.AttachEvent("onmousewheel", this.OnMouseWheel); // IE
        }

        private void InitializeRightMouseButton()
        {
            //HtmlPage.Document.GetElementById("Silverlight1").AttachEvent("oncontextmenu", this.OnContextMenu);
        }
        # endregion

        # region Utilities

        private Point pixel2point(double pixelX, double pixelY)
        {
            
            if (stxtXMax.Text == string.Empty || stxtXMin.Text == string.Empty)
            {
                Point pointNull = new Point(0, 0);
                return pointNull;
            }

            // Make sure we use the right number format

            //Get the current culture
            CultureInfo ci = Thread.CurrentThread.CurrentUICulture;
            //Get number format for culture
            string numSep = ci.NumberFormat.NumberDecimalSeparator;
            //Replace any occurences of . or , with the correct number separator
            stxtXMax.Text = stxtXMax.Text.Replace(",", numSep);
            stxtXMax.Text = stxtXMax.Text.Replace(".", numSep);
            stxtXMin.Text = stxtXMin.Text.Replace(",", numSep);
            stxtXMin.Text = stxtXMin.Text.Replace(".", numSep);
            stxtYMax.Text = stxtYMax.Text.Replace(",", numSep);
            stxtYMax.Text = stxtYMax.Text.Replace(".", numSep);
            stxtYMin.Text = stxtYMin.Text.Replace(",", numSep);
            stxtYMin.Text = stxtYMin.Text.Replace(".", numSep);
            double RealmapWidth = Convert.ToDouble(stxtXMax.Text) - Convert.ToDouble(stxtXMin.Text);
            double RealmapHeight = Convert.ToDouble(stxtYMax.Text) - Convert.ToDouble(stxtYMin.Text);

            double mapWidth = MapImg.Width;
            double mapHeight = MapImg.Height;
            double xperc;
            double yperc;
            xperc = pixelX / mapWidth;
            yperc = (mapHeight - pixelY) / mapHeight;
            double Realx = Convert.ToDouble(stxtXMin.Text) + xperc * RealmapWidth;
            double Realy = Convert.ToDouble(stxtYMin.Text) + yperc * RealmapHeight;
            Point pointMap = new Point(Realx, Realy);
            return pointMap;
        }
        private double ReturnGeoLength(double pixelX1, double pixelY1, double pixelX2, double pixelY2)
        {
            double realLength;
            double geoX1, geoY1, geoX2, geoY2;
            double Dx, Dy;
            Point pntFrom = pixel2point(pixelX1, pixelY1);
            Point pntTo = pixel2point(pixelX2, pixelY2);
            geoX1 = pntFrom.X;
            geoY1 = pntFrom.Y;
            geoX2 = pntTo.X;
            geoY2 = pntTo.Y;
            Dx = geoX2 - geoX1;
            Dy = geoY2 - geoY1;
            realLength = Math.Sqrt((Dx * Dx) + (Dy * Dy));
            realLength = Convert.ToDouble(Math.Round(Convert.ToDecimal(realLength), 2));
            return realLength;

        }

        private double ReturnGeoLength(PointCollection pntCol)
        {
            double totalLength = 0.0;
            for (int i = 0; i < pntCol.Count-1; i++)
            {
                double geoX1, geoY1, geoX2, geoY2;
                double Dx, Dy;
                Point pntFrom = pixel2point(pntCol[i].X, pntCol[i].Y);
                Point pntTo = pixel2point(pntCol[i+1].X, pntCol[i+1].Y);
                geoX1 = pntFrom.X;
                geoY1 = pntFrom.Y;
                geoX2 = pntTo.X;
                geoY2 = pntTo.Y;
                Dx = geoX2 - geoX1;
                Dy = geoY2 - geoY1;
                double segLength = Math.Sqrt((Dx * Dx) + (Dy * Dy));
                segLength = Convert.ToDouble(Math.Round(Convert.ToDecimal(segLength), 2));
                totalLength = totalLength + segLength;
            }

            return totalLength;

        }

        private void GetCoordTb( double x, double y)
        {
            //Reverse the hierarchy to go to the root Element
            FrameworkElement elRoot=(FrameworkElement)this.Parent;

            while (elRoot.Parent != null)
            {
                elRoot = (FrameworkElement)elRoot.Parent;
            }
            //Now go down the hierarchy to find all textboxes

            //var textBoxes = GetChildsRecursive(LayoutRoot).OfType<TextBox>().Where(t => t.Name == XCoordName || t.Name == YCoordName);
            var textBoxes = GetChildsRecursive(elRoot);
            foreach (TextBox tb in textBoxes)
            {
                if (tb.Name == XCoordName) tb.Text=x.ToString();
                if (tb.Name == YCoordName) tb.Text = y.ToString();
            }
          
            
        }

        private IEnumerable<DependencyObject> GetChildsRecursive(DependencyObject root) 
        {
             
            //elts.Add(root);
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);
                if (child.GetType() == typeof(TextBox) && (((TextBox)child).Name == XCoordName || ((TextBox)child).Name == YCoordName))
                {
                    elts.Add(child);
                }
               // elts.AddRange(GetChildsRecursive(VisualTreeHelper.GetChild(root, i)));
                GetChildsRecursive(child);
            }
           return elts;
        }
       
        #endregion

        #region Map Toolbar

        

        private void img1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Image img = sender as Image;
            // TODO: Display an image for error here
        }
        #endregion
       
        #region Identify Grid
        /// <summary>
        /// Populates the results grid with the attributes from the selected layer
        /// </summary>
        /// <param name="xmlResponse"></param>
        private void CreateIdentifyGrid(string xmlResponse)
        {
            bool hasSelection = false;
            bool isNewRec = false;
            bool blDisplayXLinkButton = false;
            string sXLinkField = string.Empty;
            if (xmlResponse == string.Empty)
            {
                return;
            }

            LegendLayers allLyr = (LegendLayers)legend.gridLegend.Tag;
            if (allLyr == null) return;
            LegendLayer aLyr = allLyr.getLayerByName(stxtActiveLayerName.Text);
            if (aLyr != null)
            {
                sXLinkField = aLyr.XLinkField;
            }
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.XmlResolver = new XmlXapResolver();
            XmlReader reader = XmlReader.Create(new StringReader(xmlResponse));
            reader.MoveToContent();
            while (reader.Read())
            {

                if (reader.NodeType == XmlNodeType.Element && reader.Name == "RESULTSET")
                {
                    hasSelection = true;
                    // Clear the data grid columns
                    gridDataResults.Columns.Clear();
                    bool blAddRb = Convert.ToBoolean(Convert.ToInt32(reader.GetAttribute("showLinkButton")));
                    string scount = reader.GetAttribute("count");
                    string sLayer = reader.GetAttribute("layertitle");
                    ResultsTitle.Text = Gaiocorp.SLMapViewer.Resources.ApplicationStrings.SearchResultsTitle + " (" + sLayer + ")";
                    ResultsTitle.Tag = reader.GetAttribute("layername");
                    //Display no of selected records
                    ResultsCount.Text = ApplicationStrings.NoOfSelRecs.ToString() + " " + scount;
                }

                if (reader.NodeType == XmlNodeType.Element && reader.Name == "SELECTEDFIELD")
                {
                    string strFieldName = reader.GetAttribute("name");
                    if (strFieldName.ToUpper().Trim() == sXLinkField.ToUpper().Trim())
                    {
                        blDisplayXLinkButton = true;
                        imgShowExtDetails.Tag = sXLinkField.ToUpper().Trim();
                    }
                    //Create grid columns
                    this.gridDataResults.Columns.Add
                           (
                              new DataGridTextColumn
                                {Header = strFieldName,
                                 Binding = new Binding(strFieldName)}
                            );
                }

                if (reader.NodeType == XmlNodeType.Element && reader.Name == "TABLE")
                {
                    isNewRec = true;
                    // Clear the data grid columns
                    gridDataResults.Columns.Clear();
                    bool blAddRb = Convert.ToBoolean(Convert.ToInt32(reader.GetAttribute("showLinkButton")));
                }
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "TABFIELD")
                {
                    string strFieldName = reader.GetAttribute("name");
                    if (strFieldName.ToUpper().Trim() == sXLinkField.ToUpper().Trim())
                    {
                        blDisplayXLinkButton = true;
                        imgShowExtDetails.Tag = sXLinkField.ToUpper().Trim();
                    }
                    //Console.WriteLine(strFieldName);
                    this.gridDataResults.Columns.Add(
                            new DataGridTextColumn
                            {
                                Header = strFieldName,
                                Binding = new Binding(strFieldName)
                            });

                }
                if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "RESULT")
                {
                    break;
                }

            }
            reader.Close();

            try
            {
                if (hasSelection == true)
                    this.gridDataResults.ItemsSource = GenerateData(xmlResponse).ToDataSource();

                if (isNewRec == true)
                    this.gridDataResults.ItemsSource = GenerateNewData(xmlResponse).ToDataSource();

            }
            catch (Exception) { }
            if (blDisplayXLinkButton) btnShowExtDetails.IsEnabled = true;
            else btnShowExtDetails.IsEnabled = false;
        }
        /// <summary>
        /// Returns a IEnumerable from an XML string to be displayed in the Query results window.
        /// </summary>
        /// <param name="xmlResponse"></param>
        /// <returns></returns>
        public IEnumerable<IDictionary> GenerateData(string xmlResponse)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.XmlResolver = new XmlXapResolver();
            XmlReader reader = XmlReader.Create(new StringReader(xmlResponse));
            reader.MoveToContent();
            var dict = new Dictionary<string, object>();
            int iCount = 0;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "SELECTEDFIELD")
                {
                    iCount = iCount + 1;
                    string strFieldName = reader.GetAttribute("name");
                    string strFieldValue = reader.GetAttribute("value");
                    dict[strFieldName] = strFieldValue;
                }
                if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "RESULT")
                {
                    yield return dict;
                }

                if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "RESULTSET")
                {
                    break;
                }
            }
            reader.Close();
        }
        /// <summary>
        /// Returns a IEnumerable from an XML string to be displayed in the Query results window.
        /// </summary>
        /// <param name="xmlResponse"></param>
        /// <returns></returns>
        public IEnumerable<IDictionary> GenerateNewData(string xmlResponse)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.XmlResolver = new XmlXapResolver();
            XmlReader reader = XmlReader.Create(new StringReader(xmlResponse));
            reader.MoveToContent();
            var dict = new Dictionary<string, object>();
            int iCount = 0;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "TABFIELD")
                {
                    iCount = iCount + 1;
                    string strFieldName = reader.GetAttribute("name");
                    string strFieldValue = reader.GetAttribute("value");
                    dict[strFieldName] = strFieldValue;
                }
                if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "TABLE")
                {
                    yield return dict;
                }
            }
            reader.Close();
        }

        private void gridDataResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (gridDataResults.SelectedIndex == -1)
            {
                btnShowExtDetails.IsEnabled = false;
                btnZoomToResult.IsEnabled = false;
            }
            else
            {
                btnZoomToResult.IsEnabled = true;
            }
        }
        /// <summary>
        /// Closes results window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgCloseResult_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.brdResults.Visibility = Visibility.Collapsed;
        }
        private void xbtnCloseResults_Click(object sender, RoutedEventArgs e)
        {
            this.brdResults.Visibility = Visibility.Collapsed;
        }
        /// <summary>
        /// Zoom map to selected item in the Results grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomToResult_Click(object sender, RoutedEventArgs e)
        {
            object selItems = gridDataResults.SelectedItem;
            if (this.gridDataResults.SelectedItem != null)
            {
                var t = this.gridDataResults.SelectedItem.GetType();
                var sFID = (string)t.GetProperty("FID").GetValue(this.gridDataResults.SelectedItem, null);
                stxtRequest.Text = "<REQUEST action='IDQuery' shpid='" + sFID.ToString() + "' layer='" + ResultsTitle.Tag.ToString() + "' sessionid='" + _parameters["SessionID"] + "' />";
            }
        }
        /// <summary>
        /// Populates the textbox in the container aspx page
        /// with the value of the unique key of the layer.
        /// Could be used for for sending info to the container page so it can for example,
        /// display a form based on this value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShowExtDetails_Click(object sender, RoutedEventArgs e)
        {
            if (gridDataResults.SelectedIndex == -1)
                return;
            var t = this.gridDataResults.SelectedItem.GetType();
            string sFieldName = imgShowExtDetails.Tag.ToString();
            var sVal = (string)t.GetProperty(sFieldName).GetValue(this.gridDataResults.SelectedItem, null);

            //Check if there is a silverilight control on the SL container
            string slTargetControl = _parameters["TargetControlID"].ToString();
            if (slTargetControl == string.Empty)
                return;
            
            FrameworkElement elRoot = (FrameworkElement)this.Parent;
            while (elRoot.Parent != null)
            {
                elRoot = (FrameworkElement)elRoot.Parent;
            }
            var textBoxes = GetChildsRecursive(elRoot);
            foreach (TextBox tb in textBoxes)
            {
                if (tb.Name == slTargetControl)
                {
                    tb.Text = sVal.ToString();
                    return;
                }
            }
           
            //Check if there is a textbox control on the aspx page
            // NOTE: This textbox should have a onblur() event
            HtmlElement extText = HtmlPage.Document.GetElementById(_parameters["TargetControlID"].ToString());
            if (extText != null)
            {
                //Switch focus on the target control textbox
                extText.Focus();
                extText.SetProperty("value", sVal);
                HtmlElement txtRequest = HtmlPage.Document.GetElementById(_parameters["RequestControlID"].ToString());
                //Remove focus from the target control textbox. This should trigger the onblur() function
                // on the textbox
                txtRequest.Focus();
            }
        }

        # endregion

        # region Query Grid

        private void BindCboToLayers()
        {
            if (gridQuery.Tag == null)
            {
                if (legend.gridLegend.Tag != null)
                {
                    LegendLayers allLyr = (LegendLayers)legend.gridLegend.Tag;
                    cboLayers.Items.Clear();
                    int i = 0;
                    foreach (LegendLayer aLyr in allLyr)
                    {
                        if (aLyr.EnableActive)
                        { cboLayers.Items.Add(aLyr.Title); i++; }
                    }
                    if (i > 0)
                        cboLayers.SelectedIndex = 0;
                }
            }
        }

        private void cboLayers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int s = cboLayers.SelectedIndex;
            if (s != -1)
            {
                LegendLayers allLyr = (LegendLayers)legend.gridLegend.Tag;
                LegendLayer aLyr = allLyr.getLayerByTitle(cboLayers.SelectedItem.ToString());
                lsAttrs.Items.Clear();
                foreach (LayerField aField in aLyr.Fields)
                {
                    lsAttrs.Items.Add(aField.Name);
                }
                txbQSelect.Text = "SELECT * FROM " + aLyr.Title + " WHERE :";
                gridQuery.Tag = aLyr;
            }
        }

        private void lsAttrs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lsAttrs.SelectedIndex >= 0)
            {
                txtQuery.Text = txtQuery.Text + " " + lsAttrs.SelectedItem.ToString();
            }


        }
        private void lsAttrs_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            lsAttrs.SelectedIndex = -1;
        }

        private void cboOps_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ItemCollection ic = cboOps.Items;
            if (cboOps.SelectedIndex >= 0)
            {
                if (txtQuery.Text.Trim() != string.Empty)
                {
                    ComboBoxItem cbi = (ComboBoxItem)cboOps.SelectedItem;
                    txtQuery.Text = txtQuery.Text + " " + cbi.Content.ToString() + " ";
                }
            }
        }

        private void btnCloseQuery_Click(object sender, RoutedEventArgs e)
        {
            brdQuery.Visibility = Visibility.Collapsed;
        }

        private void btnDoQuery_Click(object sender, RoutedEventArgs e)
        {
            string sWhere = txtQuery.Text.Replace(@"'", @"""");
            sWhere = sWhere.Trim();
            LegendLayer aLyr = (LegendLayer)gridQuery.Tag;
            string sLayerName = aLyr.Name;
            stxtRequest.Text = "<REQUEST action='AttributeQuery' layer='" + sLayerName + "' where='" + sWhere + "' sessionid='" + _parameters["SessionID"] + "' />";
        }


        # endregion

        #region Navigate To Url
        private void GoToUrl(string sUrl)
        {
            if (HtmlPage.IsPopupWindowAllowed)
            {
                HtmlPopupWindowOptions options = new HtmlPopupWindowOptions()
                {
                    Directories = false,
                    Location = false,
                    Menubar = false,
                    Status = false,
                    Toolbar = false,
                };

                HtmlPage.PopupWindow(new Uri(sUrl), "_blank", options);
            }
            else
            {
                HtmlPage.Window.Navigate(new Uri(sUrl), "_blank");
            
            }
        }


        #endregion

        #region Measure Tool


        #endregion

        #region Print Tool

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            ComboBoxItem cbi = (ComboBoxItem)cboPaperSizes.SelectedItem;
            if (stxtRequest.Text == "<REQUEST action='Print' pscale='" + txtPrintScale.Text + "' psize='" + cbi.Tag.ToString() + "' sessionid=" + _parameters["SessionID"] + "' />")
            {
                stxtRequest_TextChanged(stxtRequest, null);
            }
            else
                stxtRequest.Text = "<REQUEST action='Print' pscale='" + txtPrintScale.Text + "' psize='" + cbi.Tag.ToString() + "' sessionid='" + _parameters["SessionID"] + "' />";
        }

        private void btnPrintClose_Click(object sender, RoutedEventArgs e)
        {
            brdPrint.Visibility = Visibility.Collapsed;
        }
        #endregion
    }
}
